package com.ccl.service.impl;

import com.ccl.dao.ArticleMapper;
import com.ccl.dao.CommentMapper;
import com.ccl.dao.StatisticMapper;
import com.ccl.utils.EmailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class EmailService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private StatisticMapper statisticMapper;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private EmailUtils emailUtils;
    //定时发送邮件到QQ邮箱
    @Scheduled(cron = "0 0 12 * * *")
    public void sendTemplateEmail() throws MessagingException {
        String to ="1809885134@qq.com";
        String subject="博客小站统计数据";
        //采用的模板页面，处理模板页面
        //准备模板页面需要的数据:
        //文章总数
        int articlesNum = articleMapper.getArticlesNum();
        //总评论数
        Integer commentsNum = commentMapper.getCommentsNum();
        //总点击量
        int hitsNum = statisticMapper.getHitsNum();
        //创建一个context对象
        Context context = new Context();
        //往context中保存数据
        context.setVariable("articlesNum",articlesNum);
        context.setVariable("commentsNum",commentsNum);
        context.setVariable("hitsNum",hitsNum);
        //处理模板页面
        String content = templateEngine.process("comm/email", context);
        //测试发送邮件
        emailUtils.sendEmail(to,subject,content);
    }

}
